from sqlalchemy import Column, String, create_engine, MetaData, Table, func, event, exc
from sqlalchemy.orm import sessionmaker, scoped_session
from sqlalchemy.types import *
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.sql import *
from sqlalchemy.ext.declarative import synonym_for
from config import *
import platform, os

base = declarative_base()


develop = load_debug()
engine = create_engine(load_mysql_uri(),
                       echo=develop,pool_recycle=300)

metadata = MetaData(engine)
import datetime


@event.listens_for(engine, "connect")
def connect(dbapi_connection, connection_record):
    connection_record.info['pid'] = os.getpid()


@event.listens_for(engine, "checkout")
def checkout(dbapi_connection, connection_record, connection_proxy):
    pid = os.getpid()
    if connection_record.info['pid'] != pid:
        connection_record.connection = connection_proxy.connection = None
        raise exc.DisconnectionError(
            "Connection record belongs to pid %s, "
            "attempting to check out in pid %s" %
            (connection_record.info['pid'], pid)
        )


###########################################
#   相关表区域
#
###########################################
class PkgsTable(base):
    __tablename__ = "pkgs"
    id = Column(Integer, primary_key=True, autoincrement='auto')
    pkgName = Column(String)
    pkgUrl = Column(String)





##############################################
#               结束表相关
#
##############################################


# engine = create_engine("mysql+pymysql://benchmark:hLdXZzh1rQ5IYk8bU4NQ@192.168.5.134:3306/benchmark?charset=utf8",echo=develop)

SessionType = scoped_session(sessionmaker(bind=engine, expire_on_commit=False))


def GetSession():
    return SessionType()


from contextlib import contextmanager


@contextmanager
def session_scope():
    session = GetSession()
    try:
        yield session
        session.commit()
    except:
        session.rollback()
        raise
    finally:
        session.close()


def check_table_exist(tablename):
    with session_scope() as sess:
        r = sess.execute(
            "select TABLE_NAME from INFORMATION_SCHEMA.TABLES where TABLE_NAME='" + tablename + "' AND TABLE_SCHEMA='"+load_config()["mysql"]["dbname"]+"';")
        if len(r.fetchall()) >= 1:
            return True
        else:
            return False


if __name__ == '__main__':
    base.metadata.create_all(engine)
    # ad = AdTable()
    # ad.create(engine)
    # 检查表是否存在
    # r = check_table_exist("aiaiai")
    # print(r)

    # 建表测试
    # chapterTableExample.name='aiaiai'
    # chapterTableExample.create(engine)

    ## 插入测试
    # with session_scope() as sess:
    #     ci = chapterTableExample.insert()
    #     data = {
    #         "createtime":datetime.datetime.now(),
    #         "modifytime":datetime.datetime.now(),
    #         "bookid":2,
    #         "name":"测试2",
    #         "content":"content2"
    #     }
    #     sess.execute(ci,data)

    ###

    # ct = ChapterTableExample(createtime=datetime.datetime.now(),
    #                          modifytime=datetime.datetime.now(),
    #                          bookid=1,
    #                          name="用户",
    #                          content="23333")
    # # ct.set_tablename("aiaiai")
    # sess.add(ct)

